function SFLOG(message) {
	var consoleService = Components.classes["@mozilla.org/consoleservice;1"].getService(Components.interfaces.nsIConsoleService);
	consoleService.logStringMessage("SF: " + message);
}

var gPerformanceLastURL = null;
var gPffdeliciousTagArray = [];
var gPffDeliciousTimeOut = null;
var gPffTechnoratiTimeOut = null;
var gPffOnPublishTimeOut = null;
var gPffTrackBackTemp = null;
var gPFFLastTags = null;
var gPFFLastTrackbacks = "";
var gIsDraft = false;

var performancingUI = new Object();

performancingUI.init = function() {
    var theGUID = SCRIBEFIRE_BLOG.findGUID();
	
	if (!theGUID) {
	    // There are no blogs.
		SFLOG("No blog: getBlogHistory");
	}
	else {
		try {
			SCRIBEFIRE_BLOG.guid = theGUID;
		} catch (e) {
		    SCRIBEFIRE_BLOG.guid = "";
			gPerformancingUtil.init();
			return;
		}
	}
	
	window.setTimeout(function () { performancingUI.showInlinksBlogs(); }, 2000);
	
	performancingUI.initTechnorati();
	performancingUI.doUpgrade();
	gPerformancingUtil.loadBlogs();
	
	try {
		document.getElementById("custom-ping-urls").value = gPerformancingUtil.prefs.getCharPref("customPingList");
	} catch (e) {
	    // TOOO REmove
	    alert(e);
	}
	
	if (!gPerformancingUtil.prefs.getBoolPref("onetime.accountWizard") && !SCRIBEFIRE_BLOG.guid) {
		this.launchWindow('chrome://scribefire/content/accountwizard.xul');
		gPerformancingUtil.prefs.setBoolPref("onetime.accountWizard", true);
	}
	else {
		if (!gPerformancingUtil.prefs.getBoolPref("inlinksIntroduction")) {
			try {
				document.getElementById("inlinks-panel").style.display = '';
				document.getElementById("inlinks-panel").openPopup(
					document.getElementById("tab-monetize"),
					"overlap",
					32,
					0,
					false);
				setTimeout(function () {
					document.getElementById("inlinks-panel").hidePopup();
				}, 10 * 1000);
			} catch (e) {
				document.getElementById("inlinks-panel").style.display = 'none';
			}

			gPerformancingUtil.prefs.setBoolPref("inlinksIntroduction", true);
		}
		
		if (!gPerformancingUtil.prefs.getBoolPref("zemanta.trackingOptInRequest")) {
			gPerformancingUtil.prefs.setBoolPref("zemanta.trackingOptInRequest", true);
			
			var prompts = Components.classes["@mozilla.org/embedcomp/prompt-service;1"].getService(Components.interfaces.nsIPromptService);
			
			if (prompts.confirm(null, performancingUI.getLocaleString("zemanta.optinTitle"), performancingUI.getLocaleString("zemanta.optin"))) {
				gPerformancingUtil.prefs.setBoolPref("zemanta.track", true);
			}
		}
	}
	
	setTimeout(performancingEditor.restoreState, 500);
}

performancingUI.doUpgrade = function() {
	/***************************************************************
	 * Fix for the Blogger+Feedburner problem
	 * Blogger bloggers using Feedburner could not post to their 
	 * blogs because their apiurl was redirecting to Feedburner
	 * The fix grabs a URL that will never redirect, and it should
	 * have been the apiurl in the first place.
	 ****************************************************************/
	var db = SCRIBEFIRE_DB.getDB();
	
	var select = db.createStatement("SELECT guid, url FROM "+SCRIBEFIRE_DB.blogsTable+" WHERE api LIKE ?1");
	select.bindUTF8StringParameter(0, "%feeds/posts%");
	
	try {
		while (select.executeStep()) {
			try {
				var req = new XMLHttpRequest();

				// Should be async.  Fix this.
				req.open("GET", select.getUTF8String(1), false);
				req.send(null);

				var t = req.responseText;

				var isBlogger = t.match( /(?:\<link\s*rel\=\"service.post\"\s*type\=\"\application\/atom\+xml\"\s*title\=\"\D*\S*\"\s*href=\")(.*posts\/\w*)(?=.*\")/ );

			    if (isBlogger){
					var update = db.createStatement("UPDATE "+SCRIBEFIRE_DB.blogsTable+" SET api=?1 WHERE guid=?2");
					update.bindUTF8StringParameter(0, isBlogger[1]);
					update.bindStringParameter(1, select.getString(0));
					update.execute();
			    }
			} catch (offline) {
				SFLOG(offline);
			}
		}
	} catch (e) {
		alert(e);
	} finally {
		select.reset();
	}
	
	SCRIBEFIRE_DB.closeDB();
	
	/* END BLOGGER+FEEDBURNER FIX */	
}

performancingUI.initTechnorati = function() {
    var isAuto = gPerformancingUtil.prefs.getBoolPref("extra.inserttechnorati");
    document.getElementById("performancing-technorati-tags-button").hidden = isAuto;
    document.getElementById("performancing-technorati-extrainfo").hidden = !isAuto;
}

performancingUI.launchWindow = function(xulDoc) {
    window.open(xulDoc, '_blank', 'chrome,centerscreen,resizable=yes,titlebar=yes,dependent=yes')
}

performancingUI.reLoadBlogs = function() {
    gPerformancingUtil.loadBlogs();
    performancingUI.showInlinksBlogs();
}

performancingUI.onBlogSelect = function(theListElement) {
    var theSelectedBlogUID = theListElement.getAttribute('blogGUID');
    
    performancingUI.setBlogAsSelected(theSelectedBlogUID);
}

performancingUI.getSelectedHistoryEntry = function () {
	return document.getElementById("performancing-history-list").selectedItem;
}

performancingUI.copyEntryURL = function () {
	var str = this.getSelectedHistoryEntry().getAttribute("url");
	
	var oClipBoard = Components.classes["@mozilla.org/widget/clipboardhelper;1"].getService(Components.interfaces.nsIClipboardHelper);
	oClipBoard.copyString(str);
}

performancingUI.copyEntryTitle = function () {
	var str = this.getSelectedHistoryEntry().firstChild.getAttribute("label");
	
	var oClipBoard = Components.classes["@mozilla.org/widget/clipboardhelper;1"].getService(Components.interfaces.nsIClipboardHelper);
	oClipBoard.copyString(str);
}

performancingUI.setBlogAsSelected = function(theSelectedBlogUID) {
	if (false) return;
	
	SCRIBEFIRE_BLOG.guid = theSelectedBlogUID;
    performancingUI.showCurrentBlog();
}

performancingUI.onLeftSidebarTabSelect = function(theTab) {
    var theName = "";
	
	try {
		theName = theTab.getAttribute("name");
	} catch (e) {
		theName = theTab.toString();
	}
	
    if (theName == "settings") {
        var features = "chrome,titlebar,toolbar,centerscreen";
        window.openDialog("chrome://scribefire/content/settings.xul", "scribefire-preferences", features);
        return;
    }
    
	var theNavBox = document.getElementById('main-view-tabs');
	var numberOfTabs = theNavBox.getElementsByTagName("hbox").length;

	//Close all the other boxes
	for (var i=0; i < numberOfTabs; i++) {
		theNavBox.childNodes[i].setAttribute('selected', false);
	}


	// Set the selected tab
	var theMainDeck = document.getElementById('performancing-main-content-deck');

	document.getElementById('performancing-'+ theName +'-content').setAttribute('collapsed', false);

	switch(theName){
		case 'editor':
			theMainDeck.setAttribute('selectedIndex','0');
			document.getElementById('tab-' + theName).setAttribute('selected', true);
			
		break;
		case 'about':
			theMainDeck.setAttribute('selectedIndex','2');
			
			var frame = document.getElementById("about-frame");
			
			if (frame.getAttribute("src") == 'about:blank') {
			    document.getElementById("about-frame").setAttribute("src", "http://www.scribefire.com/?referrer=about");
			}
			
			document.getElementById('tab-' + theName).setAttribute('selected', true);
			
		break;
		case 'technorati':
		case 'delicious':
		case 'promote':
			performancingUI.deliciousOnLoad();
			performancingUI.getPageInfo('delicious');
			
			performancingUI.getPageInfo('technorati');

			document.getElementById('tab-promote').setAttribute('selected', true);
			theMainDeck.setAttribute("selectedIndex", "3");
			document.getElementById("promote-tabbox").selectedIndex = 2;
		break;
		case 'monetize':
			theMainDeck.setAttribute("selectedIndex", "4");
			document.getElementById('tab-' + theName).setAttribute('selected', true);
			document.getElementById('inlinks-panel').hidePopup();
		break;
	}
	
	if (theName == 'technorati') {
		document.getElementById("promote-tabbox").selectedIndex = 0;
	}
	else if (theName == 'delicious') {
		document.getElementById("promote-tabbox").selectedIndex = 1;
	}

	// Collapse all other
	this.collapseContent(theName);
}

//We collapse the elements to keep resizing space
performancingUI.collapseContent = function(notThisOne) {
    //var theEditorEl = document.getElementById('performancing-settings-content');
    
    //Now collapse all the others
    //var contentArray = ['delicious', 'editor', 'settings', 'about', 'technorati'];
    //Only collapse elements that need to be (those that don't overdlow)
    var contentArray = ['editor', 'settings', 'about', 'promote', 'monetize'];

    for(var i = 0; i < contentArray.length ; i++){
        var theContent = document.getElementById('performancing-'+ contentArray[i] +'-content');
        if (notThisOne != contentArray[i]){
            theContent.setAttribute('collapsed', true);
        }
    }
}

performancingUI.checkSubjectEmpty = function() {
    var theSubjectEntry = performancingEditor.getTitle();
	
    if(theSubjectEntry.length < 2 ){
        var localeString = performancingUI.getLocaleString('subjectisblank');
        return confirm(localeString);
    }else{
        return true;
    }
}

performancingUI.okClearPost = function() {
    gPFFLastTags = document.getElementById("performancing-technorati-tags").value;
    gPFFLastTrackbacks = document.getElementById("performancing-trackback-textbox").value;
    var thePublishDeck = performancingEditor.getCurrentEditorDocument().getElementById('performancing-feedback-deck');
    thePublishDeck.setAttribute('selectedIndex','1');
    performancingUI.onProgressOff();
}

performancingUI.afterPublishOk = function() {
    gPFFLastTags = document.getElementById("performancing-technorati-tags").value;
    gPFFLastTrackbacks = document.getElementById("performancing-trackback-textbox").value;
	performancingUI.clearTechnoratiTags();
	gPerformancingUtil.checkCategories(false);
	performancingUI.clearTrackbacks();
	performancingEditor.closeTab(true);
}

performancingUI.onServerSend = function() {
    var thePublishDeck = performancingEditor.getCurrentEditorDocument().getElementById('performancing-publish-deck');;
    thePublishDeck.setAttribute('selectedIndex','2');
    gPffOnPublishTimeOut = window.setTimeout(function () { performancingUI.onProgressOff(); },60000);
}

performancingUI.onProgressOff = function() {
    var thePublishDeck = performancingEditor.getCurrentEditorDocument().getElementById('performancing-publish-deck');
    thePublishDeck.setAttribute('selectedIndex','0');
}

performancingUI.setBlogStatus = function () {
	try {
		var blogStatus = document.getElementById("blog-group").selectedItem.blogName;
	} catch (e) {
		var blogStatus = this.getLocaleString('noblogselected');
	}
	
	var publishButtonLabel = this.getLocaleString("publishToBlog", [ blogStatus ]);
	performancingEditor.setPublishButtonLabel(publishButtonLabel);
}

performancingUI.showCurrentBlog = function() {
	var guid = SCRIBEFIRE_BLOG.guid;
	
	if (guid) {
		document.getElementById("tag-container").hidden = !SCRIBEFIRE_BLOG.supportsTags;

		window.setTimeout(gPerformancingUtil.getBlogHistory, 0, guid);
		window.setTimeout(gPerformancingUtil.getCategoryList, 0, guid);
		gPerformancingUtil.setUpAPISpecificFunctions(guid);
    }
    
    //Now show it selected
	var blogGroup = document.getElementById("blog-group");
	var blogItems = blogGroup.getElementsByTagName("radio");
	var numberOfBlogs = blogItems.length;

	for (var i = 0; i < numberOfBlogs; i++){
		var theGUID = blogItems[i].getAttribute("blogGUID");
		if (theGUID == SCRIBEFIRE_BLOG.guid){
			blogGroup.selectedItem = blogItems[i];
			break;
		}
	}
	
	this.setBlogStatus();
	
	// Enable "jump" button for certain platforms.
	if (SCRIBEFIRE_BLOG.type.match(/wordpress|moveabletype/)) {
		performancingEditor.setSplitterButton(false);
	}
	else {
		performancingEditor.setSplitterButton(true);
	}
}

performancingUI.openInTab = function(aURL) {
    var myLastWin = performancingUI.getLastWindow();
    var editorInTab = myLastWin.getWebBrowser().addTab(aURL);
    myLastWin.getWebBrowser().selectedTab = editorInTab;
}

performancingUI.getLastWindow = function() {
    var windowManager = Components.classes['@mozilla.org/appshell/window-mediator;1'].getService();
    var windowManagerInterface = windowManager.QueryInterface( Components.interfaces.nsIWindowMediator);

    var topWindowOfType = windowManagerInterface.getMostRecentWindow( "navigator:browser" ) || windowManagerInterface.getMostRecentWindow(null);
    
	return topWindowOfType;
}

performancingUI.blogThis = function() {
	var thePageProps = this.getLastPageURInTitle();
	var theURL = thePageProps[0];
	var theTitle = thePageProps[1];

	var selectedContent = '';

	try {
		var focusedWindow = document.commandDispatcher.focusedWindow;  
		
		if (focusedWindow == window){
			focusedWindow = content;
		}
		
		selectedContent = focusedWindow.getSelection().toString();
	} catch(e) {
		selectedContent = '';
	}

	selectedContent = selectedContent.toString();

	var blogThisTemplate = gPerformancingUtil.prefs.getComplexValue("blogThisTemplate", Components.interfaces.nsISupportsString).data;
	
	var textToAppend = blogThisTemplate.replace(/\$U/g, theURL).replace(/\$T/g, theTitle).replace(/\$S/g, selectedContent);
	
	this.doInsert(textToAppend);
}

function getScribefireWindow() {
	var windowMediator = Components.classes["@mozilla.org/appshell/window-mediator;1"].getService(Components.interfaces.nsIWindowMediator);
	var enumerator = windowMediator.getEnumerator("");
	
	while (enumerator.hasMoreElements()) {
		var win = enumerator.getNext();
		
		if (win.location == "chrome://scribefire/content/scribefire.xul") {
			win.focus();
			return win;
		}
		else {
			var splitScreen = win.document.getElementById("perFormancingMidasFrame");
			
			if (splitScreen && splitScreen.getAttribute("src") == 'chrome://scribefire/content/scribefire.xul') {
				var splitScreenContainer = win.document.getElementById("performancing-outerbox");
				
				if (splitScreenContainer.getAttribute("collapsed") != "true") {
					splitScreen.contentWindow.focus();
					return splitScreen.contentWindow;
				}
			}
		}
	}
	
	var browserEnumerator = windowMediator.getEnumerator("navigator:browser");
	
	// Check all of the tabs for ScribeFire
	while (browserEnumerator.hasMoreElements()) {
		var browserInstance = browserEnumerator.getNext().getWebBrowser();
		
		// Check each tab of this browser instance
		var numTabs = browserInstance.tabContainer.childNodes.length;
		
		for(var index = 0; index < numTabs; index++) {
			if (browserInstance.getBrowserAtIndex) {
				var currentBrowser = browserInstance.getBrowserAtIndex(index);
				if (currentBrowser.currentURI.spec == 'chrome://scribefire/content/scribefire.xul') {
					browserInstance.selectedTab = browserInstance.tabContainer.childNodes[index];
				
					if (currentBrowser.contentWindow.wrappedJSObject) {
						return currentBrowser.contentWindow.wrappedJSObject;
					}
				
					return currentBrowser.contentWindow;
				}
			}
		}
	}
	
	return false;
}

performancingUI.doInsert = function(textToAppend) {
	var win = getScribefireWindow();
	
	if (win) {
		win.performancingEditor.insertText(textToAppend);
	}
	else {
		var str = Components.classes["@mozilla.org/supports-string;1"].createInstance(Components.interfaces.nsISupportsString);
		str.data = textToAppend;
		gPerformancingUtil.prefs.setComplexValue("blogThisText", Components.interfaces.nsISupportsString, str);
		gperformancing.open();
	}
};

performancingUI.openAboutFromEM = function() {
	var win = getScribefireWindow();
	
	if (win) {
		win.performancingUI.onLeftSidebarTabSelect('about');
	}
	else {
		gPerformancingUtil.prefs.setCharPref("pendingPane", "about");
    	gperformancing.open();
	}
}

performancingUI.openTechnorati = function() {
	var win = getScribefireWindow();
	
	if (win) {
		win.performancingUI.onLeftSidebarTabSelect('technorati');
	}
	else {
		gPerformancingUtil.prefs.setCharPref("pendingPane", "technorati");
    	gperformancing.open();
	}
}

performancingUI.openDelicious = function() {
	var win = getScribefireWindow();
	
	if (win) {
		win.performancingUI.onLeftSidebarTabSelect('delicious');
	}
	else {
		gPerformancingUtil.prefs.setCharPref("pendingPane", "delicious");
    	gperformancing.open();
	}
};

performancingUI.updateCustomPingList = function (list) {
	gPerformancingUtil.prefs.setCharPref("customPingList", list);
};

performancingUI.showInlinksBlogs = function() {
    var inlinksDeck = document.getElementById("inlinks-deck");
    inlinksDeck.selectedIndex = 1;
    
    var inlinksBlogs = document.getElementById("compatible-blogs");
    
    while (inlinksBlogs.firstChild) {
        inlinksBlogs.removeChild(inlinksBlogs.firstChild);
    }
    
    var compatible_blogs = [];
    
	var db = SCRIBEFIRE_DB.getDB();
	var select = db.createStatement("SELECT name, url FROM "+SCRIBEFIRE_DB.blogsTable+" WHERE (type LIKE 'wordpress%' AND NOT url LIKE '%wordpress.com%') OR (type IN ('moveabletype_cust','typepad_com','drupal_cust','metaweblog_cust'));");
	
	try {
		while (select.executeStep()) {
		    compatible_blogs.push({"name": select.getString(0), "url": select.getString(1) });
		}
	} catch (e) {
	} finally {
		select.reset();
	}
	
	SCRIBEFIRE_DB.closeDB();
	
	if (compatible_blogs.length > 0) {
	    inlinksDeck.selectedIndex = 0;
	    
	    for (var i = 0; i < compatible_blogs.length; i++) {
	        var l = document.createElement("label");
	        l.setAttribute("class","text-link plain");
	        l.setAttribute("value", compatible_blogs[i].name);
	        l.setAttribute("href", compatible_blogs[i].url);
	        
	        inlinksBlogs.appendChild(l);
        }
    }
}

performancingUI.clearTechnoratiTags = function() {
    gPFFLastTags = document.getElementById("performancing-technorati-tags").value;
    document.getElementById("performancing-technorati-tags").value = "";
}

performancingUI.insertTechnorati = function() {
    var regXP = /class\=\"performancingtags/;
    if( !performancingUI.checkIfContentMatch(regXP) ){
        var theTagList = document.getElementById("performancing-technorati-tags").value;
        if(theTagList != "" && theTagList != " " ){
            //First clear out spaces following ','.
            var re = /\,\s+/g;
            theTagList = theTagList.replace(re, ",");
            
            var theTagArrayList = theTagList.split(",");
            var theTagLinkArray = [];
            for(i=0; i < theTagArrayList.length; i++ ){
                theTagLinkArray.push( this.createTechnoratiLinksArray( theTagArrayList[i] ) );
            }
            performancingUI.doechnoratiLinksInsert( theTagLinkArray );
        }
        
        return true;
    }
    
    return false;
}

performancingUI.createTechnoratiLinksArray = function(aTagName){
    var aTagLink = "<a class=\"performancingtags\" href=\"http://technorati.com/tag/_tagname_\" rel=\"tag\">_tagname_</a>";
    //turn double spaces to single space
    var re = /\s\s+/g;
    aTagName = aTagName.replace(re, " ");
    
    var re = /_tagname_/g;
    aTagLink = aTagLink.replace(re, aTagName);
    //alert("theTagLink: " + theTagLink);
    return aTagLink;
}

performancingUI.doechnoratiLinksInsert = function(theTagLinkArray) {
    var textToAppend = performancingUI.getLocaleString('technoratitags', []);
    
    for(i=0; i < theTagLinkArray.length; i++ ){
        if(i == theTagLinkArray.length-1){
            textToAppend = textToAppend + " " + theTagLinkArray[i] + "";
        }else{
            textToAppend = textToAppend + " " +	 theTagLinkArray[i] + ",";
        }
    }
    
    if(theTagLinkArray.length > 0){
        performancingUI.appendText( textToAppend );
    }
}

performancingUI.checkIfContentMatch = function(theRegExp) {
    var theContent = performancingEditor.getContent();

    if(theContent != null){
        if(theRegExp.test(theContent)){
            return true;
        }
    }
    return false;
}

performancingUI.appendText = function(theText) {
	performancingEditor.insertText(theText);
}

performancingUI.getLastPageURInTitle = function(){
    var theWindow = performancingUI.getLastWindow();

	if (!theWindow || !theWindow.content) { return ['', '', '']; }
	
    var docWrapper = new XPCNativeWrapper(theWindow.content);
    var theURL = docWrapper.location.href;
    var theTitle = docWrapper.document.title
	var theSelection = docWrapper.getSelection();
    return [theURL, theTitle, theSelection];
}

performancingUI.getPageInfo = function(anAction){
    var myLastWin = performancingUI.getLastWindow();
    var thePageProps = this.getLastPageURInTitle();
    var theURL = thePageProps[0];
    var theTitle = thePageProps[1];
    //var theURL = Components.lookupMethod(myLastWin._content, 'location').call(myLastWin._content).href;
    //var theTitle = Components.lookupMethod(myLastWin._content.document, 'title').call(myLastWin._content.document);
    var performancingSplinter = myLastWin.document.getElementById("performancingSplit");
    if( theURL != gPerformanceLastURL ){
        if(anAction == 'technorati'){
            if( !performancingSplinter || !performancingSplinter.collapsed ){
                document.getElementById("performancing-technorati-loading-img").hidden = false;
                //document.getElementById("performancing-technorati-title").value = "Loading...";
                var weAreLoading = performancingUI.getLocaleString('loading', []);
                document.getElementById("performancing-technorati-title").value = weAreLoading;
                //var RSSurl = 'http://technorat.com/node/feed/';
                var RSSurl = 'http://feeds.technorati.com/cosmos/rss/?url=' + encodeURIComponent(theURL);
                
                //Set the Title
                document.getElementById("performancing-technorati-currentpagetitle").value = theTitle;
                gPerformanceLastURL = theURL;
                performancingUI.technoratiSetTimeOut();
                //PffXmlHttpReq( aUrl, aType, aContent, aDoAuthBool, aUser, aPass)
                var theCall = new PffXmlHttpReq(RSSurl, "POST", '', false, null, null);
                
                theCall.onResult = function( aText, aXML ){
                    performancingUI.setPageInfo( aText, theTitle );
                }
                theCall.onError = function (aStatusMsg, Msg) {
                    //foo
                }
                theCall.prepCall(); //Set up The call (open connection, etc.)
                theCall.request.setRequestHeader("Content-Type", "text/xml");
                theCall.makeCall(); //Make the call
                theCall.request.overrideMimeType ('text/xml');
            }
        }else if(anAction == 'delicious'){
            performancingUI.deliciousClearBM();
            document.getElementById("performancing-delicious-bookmark-url").value = theURL;
            document.getElementById("performancing-delicious-bookmark-desc").value = theTitle;
            performancingUI.deliciousGetPageInfo(theURL);
        }
    }
}

performancingUI.setPageInfo = function(theData, thePageTitle) {
    performancingUI.technoratiClearTimeOut();
    var re = /(\<\?\xml[0-9A-Za-z\D]*\?\>)/;
    var newstr = theData.replace(re, "");
    var theXML = new XML(newstr);
    //gPFFTempObject.push(theXML);
    var t = new Namespace("tapi", "http://api.technorati.com/dtd/tapi-002.xml")
    var theInboundBlogNum = theXML.channel.t::["result"].t::["inboundblogs"].toString();
    var theInboundLinkNum = theXML.channel.t::["result"].t::["inboundlinks"].toString();
    if(theInboundBlogNum == null || theInboundBlogNum == "" ){
        theInboundBlogNum = "0";
    }
    if(theInboundLinkNum == null || theInboundLinkNum == "" ){
        theInboundLinkNum = "0";
    }
    
    var numberOfItems = theXML.channel.item.length();
    gPerformancingUtil.clearCheckListOut("performancing-technorati-inboundlinks");
    for(i = 0; i<numberOfItems && i < 10; i++ ){
        performancingUI.addItemToTechnoratiList(theXML.channel.item[i].title, theXML.channel.item[i].link);
    }

    document.getElementById("performancing-technorati-moreresults").setAttribute('onclick', "performancingUI.openInTab('" + theXML.channel.link + "/');")
    
    //Now set the info:
    document.getElementById("performancing-technorati-linkcount").value = theInboundLinkNum;
    document.getElementById("performancing-technorati-blogcount").value = theInboundBlogNum;
    document.getElementById("performancing-technorati-loading-img").hidden = true;
    document.getElementById("performancing-technorati-title").value = "Technorati";
}

performancingUI.addItemToTechnoratiList = function(aTitle, aURL){
    var theVbox = document.getElementById('performancing-technorati-inboundlinks');
    var theLabel = document.createElement('label');
    theLabel.setAttribute('value', " " +aTitle);
    theLabel.setAttribute('class', 'url performancerssitem');
    theLabel.setAttribute('maxwidth', '300px');
    theLabel.setAttribute('crop', 'right');
    theLabel.setAttribute('style', 'font-size: x-small');
    theLabel.setAttribute('tooltiptext', aURL);
    theLabel.setAttribute('onclick', "performancingUI.openInTab('" + aURL + "');");
    theVbox.appendChild(theLabel);
}

performancingUI.onTechnoratiKeyPress = function(anEvent){
    if(anEvent.keyCode == 13){
            performancingUI.onTechnoratiSearch();
    }
}

performancingUI.onTechnoratiSearch = function(){
    var itemURL = 'http://technorati.com/search/' + document.getElementById('performancing-technorati-srchtechnorati').value;
    performancingUI.openInTab(itemURL);
}

performancingUI.technoratiSetTimeOut = function(){
    gPffTechnoratiTimeOut = window.setTimeout(function () { performancingUI.technoratiOnTimeOut(); }, 20000);
}

performancingUI.technoratiOnTimeOut = function(){
    var errorMessage = performancingUI.getLocaleString('technoratitimeout', []);
    //Sorry, Technorati has timed out. Their service might be down or unstable, please try again.
    alert(errorMessage);
}

performancingUI.technoratiClearTimeOut = function(){
    window.clearTimeout(gPffTechnoratiTimeOut);
}
//
performancingUI.deliciousSetTimeOut = function(){
    gPffDeliciousTimeOut = window.setTimeout(function () { performancingUI.deliciousOnTimeOut(); }, 20000);
}

performancingUI.deliciousOnTimeOut = function(){
    //alert("Sorry, Delicious has timed out. Their service might be down or unstable, please try again.");
    //Login
    document.getElementById('performancing-delicious-loading-img').hidden = true;
    //Save Bookmark
    document.getElementById('performancing-delicious-saving-img').hidden = true;
}

performancingUI.deliciousClearTimeOut = function(){
    window.clearTimeout(gPffDeliciousTimeOut);
}

performancingUI.deliciousOnLoad = function(){
    var savePassword = gPerformancingUtil.prefs.getBoolPref("extra.delicious.savePassword");
    if(savePassword){
        var theUserName = gPerformancingUtil.prefs.getCharPref("extra.delicious.login");
        if(theUserName != "" && theUserName != "null" ){
			var thePassword = gPerformancingUtil.goGetPassword(theUserName, "pff-delicious");
			
            document.getElementById('performancing-delicious-login-username').value = theUserName;
            document.getElementById('performancing-delicious-login-password').value = thePassword;
            performancingUI.deliciousLogin();
        }
    }
    document.getElementById('performancing-delicious-login-save').checked = savePassword;
}

performancingUI.deliciousOnSaveCheck = function(){
    var savePassword = document.getElementById('performancing-delicious-login-save').checked;
    gPerformancingUtil.prefs.setBoolPref("extra.delicious.savePassword", savePassword);
}

performancingUI.doDeliciousCall = function(theURL, message, theAction, userName, passWord, doAuth){
    //PffXmlHttpReq( aUrl, aType, aContent, aDoAuthBool, aUser, aPass)
    var theCall = new PffXmlHttpReq(theURL, "GET", message, doAuth, userName, passWord);
    
    theCall.onResult = function( aText, aXML ){
        performancingUI.deliciousResponse( aText, message, theAction, userName, passWord);
    }
    theCall.onError = function (aStatusMsg, Msg) {
        //foo
    }
    theCall.prepCall(); //Set up The call (open connection, etc.)
    theCall.request.setRequestHeader("Content-Type", "text/xml");
    theCall.makeCall(); //Make the call
    theCall.request.overrideMimeType ('text/xml');
}

performancingUI.deliciousLogin = function(){
    document.getElementById('performancing-delicious-loading-img').hidden = false;
    performancingUI.deliciousSetTimeOut();
    if( performancingUI.deliciousIsLoggedIn() ){
        //performancingUI.getPageInfo('delicious');
    }else{
        var theUserName = gPerformancingUtil.prefs.getCharPref("extra.delicious.login");
        var userName = document.getElementById('performancing-delicious-login-username').value;
        var passWord = document.getElementById('performancing-delicious-login-password').value;
        
        if(theUserName != 'null' && (userName == "" || passWord == "" )){
            var errorMessage = performancingUI.getLocaleString('delicioususererror', []);
            //Please make sure you have entered a Username and Password
            alert(errorMessage);
        }else{
            performancingUI.doDeliciousCall('https://api.del.icio.us/v1/posts/update', '', 'login', userName, passWord, true);
        }
    }
}

performancingUI.deliciousResponse = function(aResponse, aMessage, anAction, userName, passWord){
    //alert('Response Baby: ' +aResponse);
    //If save password
    //var savePassword = gPerformancingUtil.prefs.getBoolPref("extra.delicious.savePassword");
    var re = /(\<\?\xml[0-9A-Za-z\D]*\?\>)/;
    var newResponse = aResponse.replace(re, "");
        
    switch(anAction){
        case 'login':
            performancingUI.deliciousClearTimeOut();
            if(newResponse.search("update time") != -1 ){//If we really logged in
                var savePassword = document.getElementById('performancing-delicious-login-save').checked;
                if(savePassword){
                    var addedUser = gPerformancingUtil.usermanagment.storeLoginDetails(userName, passWord, "pff-delicious");
                    gPerformancingUtil.prefs.setCharPref("extra.delicious.login", userName);
                }
                document.getElementById('performancing-delicious-deck').setAttribute('selectedIndex', '1');
                performancingUI.getPageInfo('delicious');
                performancingUI.getTags('delicious');
            }else{
                var errorMessage = performancingUI.getLocaleString('deliciousloginerror', []);
                //Error logging into Del.Icio.Us, please check your username and password, and try again.
                alert(errorMessage + "\n" + newResponse);
            }
            document.getElementById('performancing-delicious-loading-img').hidden = true;
            break;
            
        case 'pageInfo':
            var myXML = new XML(newResponse);
            if(myXML.post.length() >= 1){
                document.getElementById('performancing-delicious-bookmark-url').value = myXML.post.@href;
                document.getElementById('performancing-delicious-bookmark-desc').value = myXML.post.@description;
                var theTags = myXML.post.@tag;
                if(theTags == "system:unfiled"){
                    theTags="";
                }
                document.getElementById('performancing-delicious-bookmark-tags').value = theTags;
                document.getElementById('performancing-delicious-bookmark-notes').value = myXML.post.@extended;
            }
            break;
            
        case 'createbm':
            //alert('Created Bookmark');
            performancingUI.deliciousClearTimeOut();
            document.getElementById('performancing-delicious-saving-img').hidden = true;
            performancingUI.deliciousClearBM();
            performancingUI.getTags('delicious');
            break;
            
        case 'getTags':
            var myXML = new XML(newResponse);
            gPffdeliciousTagArray = [];
            if(myXML.tag.length() >= 1){
                for(i=0; i < myXML.tag.length(); i++){
                    gPffdeliciousTagArray.push( myXML.tag[i].@tag );
                }
            }
            performancingUI.deliciousLoadTags();
            break;
            
    }
    //
    
}

performancingUI.deliciousGetPageInfo = function(aURL){
    if( performancingUI.deliciousIsLoggedIn() ){
        performancingUI.doDeliciousCall('https://api.del.icio.us/v1/posts/get?url='+aURL, '', 'pageInfo', '', '', false);
    }
}

performancingUI.deliciousIsLoggedIn = function(){
    if ( document.getElementById('performancing-delicious-deck').getAttribute('selectedIndex') == '1' ){
        return true;
    }
    return false;
}

performancingUI.deliciousPostBookmark = function(){
     if( performancingUI.deliciousIsLoggedIn() ){
        performancingUI.deliciousSetTimeOut();
        document.getElementById('performancing-delicious-saving-img').hidden = false;
        var theUrl = document.getElementById('performancing-delicious-bookmark-url').value;
        var theDesc = document.getElementById('performancing-delicious-bookmark-desc').value;
        var theNotes = document.getElementById('performancing-delicious-bookmark-notes').value;
        var theTags = document.getElementById('performancing-delicious-bookmark-tags').value;
        performancingUI.doDeliciousCall('https://api.del.icio.us/v1/posts/add?url='+theUrl+'&description='+theDesc+'&extended='+theNotes+'&tags='+theTags, '', 'createbm', '', '', false);
    }
}

performancingUI.deliciousClearBM = function(){
    document.getElementById('performancing-delicious-bookmark-url').value = "";
    document.getElementById('performancing-delicious-bookmark-desc').value = "";
    document.getElementById('performancing-delicious-bookmark-tags').value = "";
    document.getElementById('performancing-delicious-bookmark-notes').value = "";
}

performancingUI.getTags = function(aService){
    if (aService == 'delicious') {
        window.setTimeout(function () {
                performancingUI.doDeliciousCall('https://api.del.icio.us/v1/tags/get', '', 'getTags', '', '', false); 
            }, 1000);
    }
}

performancingUI.deliciousLoadTags = function(){
    gPerformancingUtil.clearCheckListOut("performancing-delicious-tag-list");
    var userName = gPerformancingUtil.prefs.getCharPref("extra.delicious.login");
    for(i=0; i < gPffdeliciousTagArray.length; i++){
        performancingUI.deliciousAddTags(userName, gPffdeliciousTagArray[i]);
    }
}

performancingUI.deliciousAddTags = function(aName, aTag){
        var tagList = document.getElementById('performancing-delicious-tag-list');
        var theLabel = document.createElement('label');
        theLabel.setAttribute('value', " " +gPffdeliciousTagArray[i]);
        theLabel.setAttribute('class', "url");
        theLabel.setAttribute('width', "200px");
        theLabel.setAttribute('crop', "end");
        theLabel.setAttribute('onclick', "performancingUI.openInTab('" + "http://del.icio.us/"+aName+"/"+aTag+ "');");
        tagList.appendChild(theLabel);
}

performancingUI.autocomplete = function(theInput,event){
    var tmp = "";
    try{
        tmp = theInput.value.toLowerCase();
    }catch(e){
        return 1;
    }
    if (tmp == ""){
        //alert("tmp=0");
        return 1;
    }
    for (var z=0;z<gPffdeliciousTagArray.length;z++){
        var tmp2 = gPffdeliciousTagArray[z].toLowerCase();
        var count = 0;
        for (var i = 0;i<tmp.length;i++){
            if (tmp2.charAt(i) == tmp.charAt(i)){
                count++
            }
        }
        if (count == tmp.length){
            var diff = tmp2.length - tmp.length;
            if (diff <= 0) break;
            var kap = "";
            for (i=0;i<tmp2.length;i++){
                if (i >= tmp.length) kap += tmp2.charAt(i);
            }
            theInput.backspace = true;
            tmp = kap;
            
            //Insert Guessed Word
            var temp_n = theInput.value.length;
            theInput.value = gPffdeliciousTagArray[z];
            
            //Get Selection
            theInput.selectionEnd = theInput.value.length + temp_n;
            theInput.selectionStart = temp_n;
            return 0;
        }else{
            return 1;
        }
    }
    return 1;
}

//onkeyup="fareCompareA.getKeys(this,event)"
performancingUI.getKeys = function(theInput,event){
    if (theInput.value == "") {
        performancingUI.deliciousLoadTags();
    }
    
    if (event.keyCode == 8){
        //dontGetArray = "0";
        //return 0;
    }/*else if(event.keyCode == 8){
        theInput.selectionStart = theInput.selectionEnd;
    }*/
    
    if(performancingUI.autocomplete(theInput,event) == 1){
        performancingUI.deliciousAddSearch(theInput.value)
    }
}
//str.substr(0,10)
performancingUI.deliciousAddSearch = function(theInput){
    var myLength = theInput.length;
    gPerformancingUtil.clearCheckListOut("performancing-delicious-tag-list");
    var userName = gPerformancingUtil.prefs.getCharPref("extra.delicious.login");
    
    for(i=0; i < gPffdeliciousTagArray.length; i++){
        if( theInput == gPffdeliciousTagArray[i].substr(0,myLength) ){
            performancingUI.deliciousAddTags(userName, gPffdeliciousTagArray[i]);
        }
    }
}

performancingUI.deliciousAddTechnorati = function(aLink, aTitle, isAtom, atomEditURI){
    //alert("link: " + aLink + "\nTitle: " + aTitle + "\nisAtom: " + isAtom + "\natomEditURI: " + atomEditURI);
    var isChecked = document.getElementById('performancing-addto-delicious-checkbox').checked;
    if(isChecked){
        //Login
        if( !performancingUI.deliciousIsLoggedIn() ){
            performancingUI.deliciousOnLoad();
            var savePassword = gPerformancingUtil.prefs.getBoolPref("extra.delicious.savePassword");
            if(savePassword){
                performancingUI.deliciousLogin();
            }
        }
        
        var theTagList = document.getElementById("performancing-technorati-tags").value;
        if(theTagList == "" || theTagList == " "){
           theTagList = gPFFLastTags;
        }
        
        var theTagArrayList = [];
        if(theTagList != "" && theTagList != " " ){
            //First clear out spaces following ','.
            var re = /\,\s+/g;
            theTagList = theTagList.replace(re, ",");
            theTagArrayList = theTagList.split(",");
        } 
        isAtom = false; //For blogger Beta fix
        if(isAtom){
            var theCall = new PffXmlHttpReq(atomEditURI, "GET", null, false, null, null);
    
            theCall.onResult = function( aText, aXML ){
                performancingUI.addDeliciousTechnoratiATOM( aText, theTagArrayList );
            }
            theCall.onError = function (aStatusMsg, Msg) {
                //foo
            }
            theCall.prepCall(); //Set up The call (open connection, etc.)
            theCall.request.setRequestHeader("Content-Type", "text/xml");
            theCall.makeCall(); //Make the call
            theCall.request.overrideMimeType ('text/xml');
        }else{
            performancingUI.addDeliciousTechnoratiBM( aLink, aTitle, theTagArrayList );
        }
    }
}

performancingUI.addDeliciousTechnoratiBM = function(theURL, theDesc, theTags){
    var tagSpaceList = "";
    for(i=0; i < theTags.length; i++){
        tagSpaceList = tagSpaceList + " " + theTags[i];
    }
    var theCallURL = 'https://api.del.icio.us/v1/posts/add?tags='+tagSpaceList+'&url='+ encodeURIComponent(theURL) +'&description='+ encodeURIComponent(theDesc) ;
    //alert("theCallURL: " + theCallURL + " theTags: " + theTags + " gPFFLastTags: " + gPFFLastTags);
    performancingUI.doDeliciousCall(theCallURL, '', 'createbm', '', '', false);
}

performancingUI.addDeliciousTechnoratiATOM = function(aResponse, theTags){
    //Parse the post
    var re = /(\<\?\xml[0-9A-Za-z\D]*\?\>)/;
    var newstr = aResponse.replace(re, "");
    
    var t = new Namespace("tapi", "http://purl.org/atom/ns#")
    var myXML = new XML(newstr);
    var aLink  = myXML.t::link[1].@href;
    var aTitle = myXML.t::title;
    
    performancingUI.addDeliciousTechnoratiBM( aLink, aTitle, theTags );
}

performancingUI.sendTrackBacks = function(aTitle, aLink, aBlogName){
    var theTrackBackList = document.getElementById("performancing-trackback-textbox").value;
    //alert("theTrackBackList: " + theTrackBackList + " gPFFLastTrackbacks: " +gPFFLastTrackbacks);
    if(theTrackBackList != ""){
        gPFFLastTrackbacks = theTrackBackList;
    }else{
        theTrackBackList = gPFFLastTrackbacks;
    }
    if(theTrackBackList != "" && theTrackBackList != null ){
        var theTrackBackArray = [];
        if(theTrackBackList != "" && theTrackBackList.length > 4){
            theTrackBackArray = theTrackBackList.split(",");
        }
        for(i=0; i < theTrackBackArray.length; i++){
            performancingUI.trackbackCall(theTrackBackArray[i], aLink, aTitle,	aBlogName, i, false );
        }
    }
    //theTrackBackList.value = "";
}

performancingUI.trackbackCall = function( theURL, aLink, aTitle, aBlogName, aNumber, aSecondTry ){
    var theCompleteURL = theURL + "&title="+aTitle+"&url="+aLink+ "&blog_name=" +aBlogName;
    //PffXmlHttpReq( aUrl, aType, aContent, aDoAuthBool, aUser, aPass)
    var theCall = new PffXmlHttpReq(theURL, "POST", theCompleteURL, false, null, null);
    
    theCall.onResult = function( aText, aXML ){
        performancingUI.trackBackResponse( aText, theURL, theCompleteURL, 'trackback', '', aNumber, aSecondTry, '');
    }
    theCall.onError = function (aStatusMsg, Msg) {
        //foo
    }
    theCall.prepCall(); //Set up The call (open connection, etc.)
    theCall.request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    theCall.makeCall(); //Make the call
    theCall.request.overrideMimeType ('text/xml');
    
}

performancingUI.trackBackResponse = function( aData, theURL, message, theAction, additionalInfo, aNumber, aSecondTry, theGUID){
    //alert('ANumber: '+aNumber+' aSecondTry: '+aSecondTry+' and TrackBack Success: ' + aData);
    var isSuccess = "<error>0</error>";
    var isError = "<error>1</error>";
    
    var isRDF = /(?:trackback:ping=\")(.*)(?:\")/mgi;
    //var isRDF = /(?:\trackback\:\ping\=\")((http|https):\/\/[a-zA-Z0-9@:%_~#?&=.,\/;-]*[a-zA-Z0-9@:%_~#&=\/;-])(?:\".+)(?=\")/mgi;
    var isLink = /(?:\<\a\ \href\=\")((http|https):\/\/[a-zA-Z0-9@:%_~#?&=.,\/;-]*[a-zA-Z0-9@:%_~#&=\/;-])(?=\"\srel="trackback">)|(?:\<\a\ \href\=\")((http|https):\/\/[a-zA-Z0-9@:%_~#?&=.,\/;-]*[a-zA-Z0-9@:%_~#&=\/;-])(?=\"\>trackback\<)/mgi;
    //var isLink2 = /(?:\<\a\ \href\=\")((http|https):\/\/[a-zA-Z0-9@:%_~#?&=.,\/;-]*[a-zA-Z0-9@:%_~#&=\/;-])(?=\"\>trackback\<)/mgi;
    //gPffTrackBackTemp = aData;
    if( aData.search(isSuccess) != -1){ //If succesfull
        //alert('It was GOOD! aSecondTry" ' + aSecondTry);
    }else if(aData.search(isError) != -1 ){ //If error but url was right
        //alert('It was a good trackback call but got rejected! aSecondTry" ' + aSecondTry);
    }else{ // url must be wrong, let's look for a real trackback url
        if(!aSecondTry){ //Make sure it's not already the second try
            //(?:trackback:ping=\")(.*)(?:\")
            //(?:\<\a\ \href\=\")((http|https):\/\/[a-zA-Z0-9@:%_~#?&=.,\/;-]*[a-zA-Z0-9@:%_~#&=\/;-])(?:\".+)(?=rel="trackback">)
            var isAnRDF =  aData.match(isRDF);
            var isALink =  aData.match(isLink);
            //alert("isAnRDF: " + isAnRDF +"\n isALink: "+isALink );
            if(isAnRDF != null){
                isAnRDF = isAnRDF.toString().replace(/trackback:ping=\"/, ""); //We need better regexps
                isAnRDF = isAnRDF.replace(/"/, "");
                //PffXmlHttpReq( aUrl, aType, aContent, aDoAuthBool, aUser, aPass)
                var theCall = new PffXmlHttpReq(isAnRDF, "POST", message, false, null, null);
                
                theCall.onResult = function( aText, aXML ){
                    performancingUI.trackBackResponse( aText, isAnRDF, message, 'trackback', '', aNumber, true, '');
                }
                theCall.onError = function (aStatusMsg, Msg) {
                    //foo
                }
                theCall.prepCall(); //Set up The call (open connection, etc.)
                theCall.request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
                theCall.makeCall(); //Make the call
                theCall.request.overrideMimeType ('text/xml');
            }else if(isALink != null){
                isALink = isALink.toString().replace(/<a href="/, ""); //We need better regexps 
                isALink = isALink.replace(/"/, "");
                //PffXmlHttpReq( aUrl, aType, aContent, aDoAuthBool, aUser, aPass)
                var theCall = new PffXmlHttpReq(isALink, "POST", message, false, null, null);
                
                theCall.onResult = function( aText, aXML ){
                    performancingUI.trackBackResponse( aText, isALink, message, 'trackback', '', aNumber, true, '');
                }
                theCall.onError = function (aStatusMsg, Msg) {
                    //foo
                }
                theCall.prepCall(); //Set up The call (open connection, etc.)
                theCall.request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
                theCall.makeCall(); //Make the call
                theCall.request.overrideMimeType ('text/xml');
            }else{
                //alert('Fail, seems there is not a trackback link aSecondTry" ' + aSecondTry);
            }
        }
    }
}

performancingUI.clearTrackbacks = function(isClear) {
    document.getElementById("performancing-trackback-textbox").value ="";
}

//For debugging, you must have FireBug installed.
//performancingUI.printfire(whatever);
performancingUI.printfire = function(){
    if (document.createEvent)
    {
        printfire.args = arguments;
        var ev = document.createEvent("Events");
        ev.initEvent("printfire", false, true);
        dispatchEvent(ev);
    }
}

performancingUI.doPing = function( theBlogName, theBlogURL ){
	if (document.getElementById("performancing-enablepings-checkbox").checked) {
		var tempArray = [];
		
		try {
			var selectedPing = document.getElementById("performancing-pingradio-group").selectedItem.value;
		} catch (e) {
			return;
		}
		
		if(selectedPing == 'custom'){
			var checkList = document.getElementById("performancing-pinglist-vbox");
		
			for(var i = 0; i < checkList.childNodes.length; i++ ){
				try {
					if (checkList.childNodes[i].checked){
						var tempString = checkList.childNodes[i].getAttribute("url");
						tempArray.push(tempString);
					}
				} catch(e) {
				}
			}
			
			var otherPings = gPerformancingUtil.prefs.getCharPref("customPingList");
			
			if (otherPings.length > 0) {
				otherPingsArray = otherPings.split(/[,\s]/);
			}
			
			tempArray = tempArray.concat(otherPingsArray);
			
			if(tempArray.length > 0){
				for (var x = 0; x < tempArray.length; x++){
					if (tempArray[x]) {
						// (There may be blank values in this array.)
						performancingUI.doRPCPing(theBlogName, theBlogURL, tempArray[x]);
					}
				}
			}
		}
		else{
			switch(selectedPing){
				case 'pingomatic':
					var theRestURL = "http://pingomatic.com/ping/?title="+theBlogName+"&blogurl="+theBlogURL+"&rssurl=http%3A%2F%2F&chk_weblogscom=on&chk_blogs=on&chk_technorati=on&chk_feedburner=on&chk_syndic8=on&chk_newsgator=on&chk_feedster=on&chk_myyahoo=on&chk_pubsubcom=on&chk_blogdigger=on&chk_blogrolling=on&chk_blogstreet=on&chk_weblogalot=on&chk_icerocket=on";
					performancingUI.doRestPing(theBlogName, theBlogURL, theRestURL);
				break;
				case 'pingoat':
					var theRestURL = "http://pingoat.com/index.php?pingoat=go&blog_name="+theBlogName+"&blog_url="+theBlogURL+"&rss_url=http%3A%2F%2F&cat_0=0&id%5B%5D=0&id%5B%5D=1&id%5B%5D=2&id%5B%5D=3&id%5B%5D=4&id%5B%5D=5&id%5B%5D=6&id%5B%5D=7&id%5B%5D=10&id%5B%5D=11&id%5B%5D=12&id%5B%5D=14&id%5B%5D=16&id%5B%5D=20&cat_1=0&cat_2=0";
					performancingUI.doRestPing(theBlogName, theBlogURL, theRestURL);
				break;
			}
		}
	}
}

performancingUI.doRestPing = function( theBlogName, theBlogURL, theRestURL ){
    //Now make RPC Call
    var theCall = new PffXmlHttpReq(theRestURL, "GET", null, false, null, null);
    
    theCall.onResult = function( aText, aXML ){
        performancingUI.processPingRecData( aText, "", "ping");
    }
    theCall.onError = function (aStatusMsg, Msg) {
    }
    theCall.prepCall(); //Set up The call (open connection, etc.)
    theCall.request.setRequestHeader("Content-Type", "text/xml");
    theCall.makeCall(); //Make the call
    theCall.request.overrideMimeType ('text/xml');
}

performancingUI.doRPCPing = function( theBlogName, theBlogURL, rpcURL ){
    var theMethodName = "weblogUpdates.extendedPing";
    var theXMLtoSend = bfXMLRPC.makePingXML(theMethodName, theBlogName, theBlogURL);
    
    //Now make RPC Call
    var theCall = new PffXmlHttpReq(rpcURL, "POST", theXMLtoSend, false, null, null);
    
    theCall.onResult = function( aText, aXML ){
        performancingUI.processPingRecData( aText, theXMLtoSend, "");
    }
    theCall.onError = function (aStatusMsg, Msg) {
    }
    theCall.prepCall();
    theCall.request.setRequestHeader("Content-Type", "text/xml");
    theCall.makeCall();
    theCall.request.overrideMimeType ('text/xml');
}


performancingUI.processPingRecData = function( aData ){
}

performancingUI.openImageInsert = function () {
	var re = [];
	var theURL = [];
	
	window.openDialog(
		"chrome://scribefire/content/imageInsert.xul",
		performancingUI.getLocaleString('imageinsertwindowtitle'),
		"chrome,modal,centerscreen",
		re,
		theURL);

	if (re[0]) {
		return theURL[0];
	}

	return false;
}

performancingUI.openImageUpload = function(ourURL, useLastMethod){
	var apiAvailable = SCRIBEFIRE_BLOG.supportsUploads;
	var ftpAvailable = SCRIBEFIRE_BLOG.ftp_username && SCRIBEFIRE_BLOG.ftp_host;
	
	if (!apiAvailable && !ftpAvailable) {
		var msg = performancingUI.getLocaleString("noUpload");
		alert(msg);
		return false;
	}
	
	var re = [];
	if (!ourURL) ourURL = "";
	var theURL = [ ourURL ];
	
	window.openDialog(
		"chrome://scribefire/content/imageUpload.xul", 
		performancingUI.getLocaleString('imageinsertwindowtitle'), 
		"chrome,modal,centerscreen", 
		re, 
		theURL, 
		useLastMethod);

	if (re[0]) {
		return theURL[0];
	}

	return false;
}

performancingUI.openFileUpload = function(){
    //alert("Ping Back: " + aData);
    var re = [];
    var ourURL = "";
    var theURL = [ourURL];
    var localeString = performancingUI.getLocaleString('fileinsertwindowtitle', []);
    window.openDialog("chrome://scribefire/content/fileUpload.xul", localeString,"chrome,modal,centerscreen",re,theURL);
    if(re[0]){
      //alert("the URL to insert: " +theURL[0]);
      return theURL[0];
    }
    return false;
}


performancingUI.onTextBoxLoad2 = function(){
	var prefsService = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefService);
	var prefs = prefsService.getBranch("performancing.");
	var isRTL = prefs.getBoolPref('display.enablertl');

	var theStyle = "";

	if(isRTL){
		theStyle = "direction:rtl;";
	}
	
	performancingEditor.setEditorStyle(theStyle);
}

performancingUI.getLocaleString = function(strName, formattingValues){
        var str = null;

        try {
            var strbundle = document.getElementById("performancingstrings");
            var strbundleFallback = document.getElementById("performancingstrings-fallback");
            if (typeof formattingValues == 'undefined' || (formattingValues.length == 0)) {
                try {
                    str = strbundle.getString("performancing." + strName);
                }catch(e) {
                    str = strbundleFallback.getString("performancing." + strName);
                }
            } else {
                try {
                    str = strbundle.getFormattedString("performancing." + strName, formattingValues);
                }catch(e) {
                    str = strbundleFallback.getFormattedString("performancing." + strName, formattingValues);
                }
            }
        } catch (err) {
        }

        return str;
}

performancingUI.hasCheckboxChildren = function(checkListIDname){
    var theCheckList = document.getElementById(checkListIDname);
    if( theCheckList.hasChildNodes() ){
        return (theCheckList.firstChild.nodeName == 'checkbox') ;
    }else{
        return false;
    }
}

performancingUI.addCategories = function(){
	var localeString = performancingUI.getLocaleString('addcategories');
    var theCategories = prompt(localeString);
	
	if ((theCategories != null) && (theCategories != "")){
		var categoryString = theCategories.replace(/\s+/g, " ").replace(/^\s+|\s+$/g, "");
		var categories = [];
		
		// We now have a comma delimited string, but it may included quoted phrases
		var currentCategory = "";
		var inQuotes = 0;
		
		for (var i = 0; i < categoryString.length; i++) {
		    var theChar = categoryString.charAt(i);
		    
			if (theChar == " " && currentCategory.length == 0) {
				continue;
			}
			
		    if (theChar == "'" || theChar == '"') {
		        if (inQuotes == theChar) {
		            inQuotes = false;
	            }
	            else if (currentCategory.length == 0){
	                inQuotes = theChar;
                }
                else {
                    currentCategory += theChar;
                }
            }
	        else {
		        if (theChar == ","){ 
		            if (!inQuotes) {
		                categories.push(currentCategory);
		                currentCategory = "";
		                continue;
	                }
	            }
	            
                currentCategory += categoryString.charAt(i);
            }
	    }
	    
	    if (currentCategory != "") categories.push(currentCategory);
		
		var theCategoryArray = categories;
		
		if (SCRIBEFIRE_BLOG.createCategories) {
			// The means that new categories can be created server-side
			// without adding them to a post right away.
			
			// Check to make sure that this category isn't in the list already.
			
			var checkList = document.getElementById("blog-sidebar-listing-categories");
			
			newCategory : for (var i = 0; i < theCategoryArray.length; i++){
				for (var j = 0; j < checkList.childNodes.length; j++) {
					if (checkList.childNodes[j].getAttribute("label") == theCategoryArray[i]){
						checkList.childNodes[j].setAttribute("checked", "true");
						continue newCategory;
					}
				}
				
				var myResponse = SCRIBEFIRE_BLOG.serviceObject.newCategory(theCategoryArray[i]);
				
				if(myResponse){
					performancing_xmlcall.sendCommand(SCRIBEFIRE_BLOG.api, myResponse, 'newcategorycall', theCategoryArray[i], "", performancing_xmlcall.processData);
				}
			}
		}
		
		performancingUI.addCategoriesToList(theCategoryArray);
	}
}

performancingUI.addCategoriesToList = function(theCategoryArray){
	var doNotCheckClear = performancingUI.hasCheckboxChildren('blog-sidebar-listing-categories');
	gPerformancingUtil.setCategoriesSidebar(theCategoryArray, !doNotCheckClear);
}

performancingUI.shareCurrentPage = function (service) {
	var pageData = this.getLastPageURInTitle();
	
	this.share(service, pageData[0].toString(), pageData[1].toString(), pageData[2].toString());
}

performancingUI.share = function(service, url, title, text) {
	if (!text) text = '';
	if (!title) title = '';
	
	switch (service) {
		case 'digg':
			var shareUrl = "http://digg.com/submit?phase=3&url="+encodeURIComponent(url)+"&title="+encodeURIComponent(title);
		break;
		case 'propeller':
			var shareUrl = 'http://www.propeller.com/submit/?U='+encodeURIComponent(url)+'&T='+encodeURIComponent(title)+'&C='+encodeURIComponent(text);
		break;
		case 'mahalo':
			var shareUrl = 'http://www.mahalo.com/Special:Suggest_A_Link?b64linkTitle='
				+btoa(title)
				+'&b64linkURL='
				+btoa(url);
		break;
		case 'reddit':
			var shareUrl = 'http://reddit.com/submit?url='+encodeURIComponent(url)+'&title='+encodeURIComponent(title);
		break;
		case 'stumbleupon':
			var shareUrl = 'http://www.stumbleupon.com/submit?url='+encodeURIComponent(url)+'&title='+encodeURIComponent(title);
		break;
		case 'facebook':
			var shareUrl = 'http://www.facebook.com/sharer.php?u='+encodeURIComponent(url)+'&t='+encodeURIComponent(title);
		break;
		case 'newsvine':
			var shareUrl = 'http://www.newsvine.com/_wine/save?u='+encodeURIComponent(url)+'&h='+encodeURIComponent(title);
		break;
		case 'fark':
			var shareUrl = 'http://cgi.fark.com/cgi/fark/submit.pl?new_url='+encodeURIComponent(url)+'&new_comment='+encodeURIComponent(title)+'&linktype=';
		break;
		case 'furl':
			var shareUrl = 'http://furl.net/storeIt.jsp?u='+encodeURIComponent(url)+'&t='+encodeURIComponent(title);
		break;
		case 'magnolia':
			var shareUrl = 'http://ma.gnolia.com/bookmarklet/add?url='+encodeURIComponent(url)+'&title='+encodeURIComponent(title);
		break;
	};
	
	if (typeof shareUrl != 'undefined') {
		this.openInTab(shareUrl);
	}
}